package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.util.NumberFormatUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserRegisterRequest;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.service.IRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * 创建日期: 2022/05/19 09:04
 *
 * @author JinLu Zhou
 */
@Service
@Slf4j
public class RegisterServiceImpl implements IRegisterService {

    @Value("${spring.mail.username}")
    private String sendMailMan;

    @Value("${email.text}")
    private String emailText;

    @Value("${custom.value2.overdue-time}")
    private String overdueTime;

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender mailSender;

    @Autowired
    RedissonClient redissonClient;

    @Override
    @Transactional
    public UserRegisterResponse register(UserRegisterRequest userRegisterRequest) {
        UserRegisterResponse userRegisterResponse = new UserRegisterResponse();
        try {
            //判空
            userRegisterRequest.requestCheck();
            //用户名是否重复、邮箱是否重复
            volidUserNameRepeat(userRegisterRequest);
            //1.向用户表插入一条记录
            Member member = new Member();
            member.setUsername(userRegisterRequest.getUserName());
            member.setEmail(userRegisterRequest.getEmail());
            //加密处理
            String userPwd = DigestUtils.md5DigestAsHex(userRegisterRequest.getUserPwd().getBytes());
            member.setPassword(userPwd);

            member.setCreated(new Date());
            member.setUpdated(new Date());
            member.setIsVerified("N");
            member.setState(1);
            int insert = memberMapper.insert(member);
            if (insert != 1) {
                userRegisterResponse.setCode(UserRetCode.USER_REGISTER_FAILED.getCode());
                userRegisterResponse.setMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
                return userRegisterResponse;
            }
            //2.向用户验证表插入一条记录
            UserVerify userVerify = new UserVerify();
            userVerify.setUsername(userRegisterRequest.getUserName());
            String key = userRegisterRequest.getUserName() + userRegisterRequest.getUserPwd() + UUID.randomUUID().toString();
            String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
            userVerify.setUuid(uuid);
            userVerify.setRegisterDate(new Date());
            userVerify.setIsExpire("N");
            userVerify.setIsVerify("N");
            int rows = userVerifyMapper.insert(userVerify);
            if (rows != 1) {
                userRegisterResponse.setCode(UserRetCode.USER_REGISTER_VERIFY_FAILED.getCode());
                userRegisterResponse.setMsg(UserRetCode.USER_REGISTER_VERIFY_FAILED.getMessage());
                return userRegisterResponse;
            }
            //3.发送用户激活邮件
            //TODO 发送用户邮件
            sendEmail(uuid, userRegisterRequest);
            //一分钟内没有激活就会将过期
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    beOverdue(userRegisterRequest.getUserName());
                }
            }, NumberFormatUtil.getMaxAge(overdueTime));
            log.info("用户注册成功,注册参数:{}", JSON.toJSONString(userRegisterRequest));
            userRegisterResponse.setCode(UserRetCode.SUCCESS.getCode());
            userRegisterResponse.setMsg(UserRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.error("RegisterServiceImpl.register occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(userRegisterResponse, e);
        }
        return userRegisterResponse;
    }

    private void beOverdue(String userName) {
        Example memberExample = new Example(Member.class);
        memberExample.createCriteria().andEqualTo("username", userName);
        Member member = memberMapper.selectByExample(memberExample).get(0);
        if("N".equals(member.getIsVerified())){
            //没认证删除
            memberMapper.deleteByExample(memberExample);
            Example verifyExample = new Example(UserVerify.class);
            verifyExample.createCriteria().andEqualTo("username", userName);
            userVerifyMapper.deleteByExample(verifyExample);

            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("CSMALL用户过期");
            message.setFrom(sendMailMan);
            message.setTo(member.getEmail());
            message.setText("您好！您在我们商城注册的账号没有及时激活已过期，请再次注册！");
            mailSender.send(message);
        }
    }

    private void sendEmail(String uuid, UserRegisterRequest userRegisterRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("CSMALL用户激活,请在一个小时内完成");
        message.setFrom(sendMailMan);
        message.setTo(userRegisterRequest.getEmail());
        message.setText(String.format(emailText, userRegisterRequest.getUserName(),uuid));
        mailSender.send(message);
    }

    private void volidUserNameRepeat(UserRegisterRequest userRegisterRequest) {
        Example usernameExample = new Example(Member.class);
        usernameExample.createCriteria().andEqualTo("username", userRegisterRequest.getUserName());
        List<Member> members0 = memberMapper.selectByExample(usernameExample);
        if (!CollectionUtils.isEmpty(members0)) {
            throw new ValidateException(UserRetCode.USERNAME_ALREADY_EXISTS.getCode(),
                    UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
        }
        Example emailExample = new Example(Member.class);
        emailExample.createCriteria().andEqualTo("email", userRegisterRequest.getEmail());
        List<Member> members1 = memberMapper.selectByExample(emailExample);
        if (!CollectionUtils.isEmpty(members1)) {
            throw new ValidateException(UserRetCode.EMAIL_ALREADY_EXISTS.getCode(),
                    UserRetCode.EMAIL_ALREADY_EXISTS.getMessage());
        }
    }
}
